<template>
  <div id="app">
    <el-upload drag action :auto-upload="false" :show-file-list="false" :on-change="changeFile" class="el-upload">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
    </el-upload>
    <div>
      <p v-if="total > 0 && total < 100">{{ Name }}--
        <span>上传进度：{{ total | totalText }}%</span>
        <el-link type="primary" v-if="total > 0 && total < 100" @click="handleBtn">{{ btn | btnText }}</el-link>
      </p>
    </div>
    <!-- PROGRESS -->
    <div class="sendfiled">
      <h1 style="text-align:left;margin-left: 30%;">已传文件</h1>
      <li v-for="item in list" :key="item.id" class="list">
        <p>
          {{ item.fileName }}
        </p>
        <div class=" progress">
          <div>
            <svg t="1740403108414" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="1647" width="20" height="20">
              <path
                d="M186.56 128h114.048c15.728 0 27.76 14.048 26.24 29.84l-0.944 6.24c-0.32 2.512-0.48 4.928-0.496 7.2 0 28.32 19.28 53.52 37.648 53.52h291.632c16.72 0 35.824-25.472 35.808-53.52 0-2.32-0.16-4.72-0.48-7.216l-0.928-6.224C687.568 142.048 699.6 128 715.328 128h112.896C911.424 128 960 182.544 960 266.32V790.88c0 92.608-46.656 137.12-137.6 137.12H192.368C105.728 928 64 879.744 64 790.848V266.32C64 177.2 100.176 128 186.56 128z"
                fill="#FFBD27" p-id="1648"></path>
              <path
                d="M404.88 96C379.936 96 360 117.44 360 143.936c0 26.56 19.984 48.064 44.88 48.064h209.056c23.68 0 43.664-21.504 43.664-48.064C657.6 117.44 637.664 96 612.672 96H404.88z"
                fill="#333333" p-id="1649"></path>
              <path
                d="M492.32 695.44a34.336 34.336 0 0 1-24.368-10.128l-137.872-138.416a34.752 34.752 0 0 1 0-48.96 34.368 34.368 0 0 1 48.736 0l113.504 113.968 216.864-217.744a34.304 34.304 0 0 1 48.736 0c13.44 13.504 13.44 35.392 0 48.912l-241.232 242.24a34.4 34.4 0 0 1-24.368 10.128z"
                fill="#FFFFFF" p-id="1650"></path>
            </svg>
          </div>
          <div class="load" @click="goLoad(item)">
            <svg t="1740406053818" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="3563" width="25" height="25">
              <path
                d="M512 909.061224c-218.906122 0-397.061224-178.155102-397.061224-397.061224s178.155102-397.061224 397.061224-397.061224 397.061224 178.155102 397.061224 397.061224-178.155102 397.061224-397.061224 397.061224z"
                fill="#16C4AF" p-id="3564"></path>
              <path
                d="M512 730.383673c-10.971429 0-19.853061-8.881633-19.853061-19.853061V313.469388c0-10.971429 8.881633-19.853061 19.853061-19.853061s19.853061 8.881633 19.853061 19.853061v397.061224c0 10.971429-8.881633 19.853061-19.853061 19.853061z"
                fill="#C3F4EA" p-id="3565"></path>
              <path
                d="M512 730.383673c-5.22449 0-9.926531-2.089796-14.106122-5.746938-7.836735-7.836735-7.836735-20.37551 0-28.212245l160.914285-160.914286c7.836735-7.836735 20.37551-7.836735 28.212245 0 7.836735 7.836735 7.836735 20.37551 0 28.212245l-160.914286 160.914286c-4.179592 3.657143-8.881633 5.746939-14.106122 5.746938z"
                fill="#C3F4EA" p-id="3566"></path>
              <path
                d="M512 730.383673c-5.22449 0-9.926531-2.089796-14.106122-5.746938l-160.914286-160.914286c-7.836735-7.836735-7.836735-20.37551 0-28.212245 7.836735-7.836735 20.37551-7.836735 28.212245 0l160.914285 160.914286c7.836735 7.836735 7.836735 20.37551 0 28.212245-4.179592 3.657143-8.881633 5.746939-14.106122 5.746938z"
                fill="#C3F4EA" p-id="3567"></path>
            </svg>
          </div>
          <div class="preview" @click="preView(item)">
            <svg t="1740453986441" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="2065" width="20" height="20">
              <path
                d="M512 853.333333c-263.9872 0-477.866667-284.672-477.866667-341.230933C34.133333 471.3472 248.0128 170.666667 512 170.666667c263.918933 0 477.866667 303.445333 477.866667 341.435733C989.7984 568.900267 775.850667 853.333333 512 853.333333z m-6.144-521.1136c-127.658667 0-276.5824 60.279467-276.5824 187.938134s148.8896 174.318933 276.548267 174.318933 279.005867-46.660267 279.005866-174.318933-151.3472-187.938133-279.005866-187.938134z m2.594133 93.7984a79.325867 79.325867 0 0 0 79.223467 79.291734c10.376533 0 19.968-2.1504 29.013333-5.563734 0.341333 3.6864 1.297067 7.202133 1.297067 11.0592a113.220267 113.220267 0 1 1-226.542933 0 113.322667 113.322667 0 0 1 113.220266-113.3568c3.1744 0 6.178133 0.7168 9.216 0.989867-3.345067 8.6016-5.4272 17.749333-5.4272 27.579733z"
                fill="#85C2FF" p-id="2066"></path>
            </svg>
          </div>
        </div>
      </li>
    </div>
    <preView class="view">
    </preView>


  </div>
</template>

<script>
import getId from './utils/uuid'
import { fileParse } from "./assets/utils";
import axios from "axios";
import SparkMD5 from "spark-md5";
import { EventBus } from './utils/EventBus'
import preView from './preView/index.vue'
export default {
  name: "fileHelp",
  data() {
    return {
      total: 0,
      video: null,
      btn: false,
      list: [],
      Name: '',
      Flag: false,
      uploadedIndices: [], // 新增已上传索引记录
    };
  },
  components: {
    preView
  },
  filters: {
    btnText(btn) {
      return btn ? "继续" : "暂停";
    },
    totalText(total) {
      return total > 100 ? 100 : total;
    },
  },
  mounted() {
    let value = JSON.parse(localStorage.getItem('list'))
    this.list = value ? value : [];
    const saved = localStorage.getItem('uploadProgress');
    if (saved) this.uploadedIndices = JSON.parse(saved);
  },
  methods: {
    async goLoad(item) {
      const fileParts = item.fileName.split('.')
      const filename = item.hash + '.' + fileParts[fileParts.length - 1];

      let result = await axios.get(`/download/${filename}`, {
        params: {
          filename: filename
        },
      }).then(() => {
        const link = document.createElement('a');
        link.href = `/download/${filename}`;
        link.download = filename; // 设置下载的文件名
        document.body.appendChild(link);  // 将链接添加到 DOM 中
        link.click();  // 触发下载
        document.body.removeChild(link);  // 下载后移除链接
      })
    },

    preView(item) {
      this.Flag = true
      const fileParts = item.fileName.split('.')
      const fixx = fileParts.pop()
      const filename = item.hash + '.' + fixx
      console.log(filename);

      if (fixx !== 'docx' && fixx !== 'xlsx' && fixx !== 'pdf' && fixx !== 'xls') {
        alert('该文件不能预览哦,仅支持docx ,xlsx ,pdf,doc,xls文件预览')
        return
      }

      EventBus.$emit('revFileName', filename)

    },
    async changeFile(file) {
      if (!file) return;
      file = file.raw; console.log(file);
      this.Name = file.name
      // 解析为BUFFER数据
      // 我们会把文件切片处理：把一个文件分割成为好几个部分（固定数量/固定大小）
      // 每一个切片有自己的部分数据和自己的名字
      // HASH_1.mp4
      // HASH_2.mp4
      // ...
      let buffer = await fileParse(file, "buffer"),
        spark = new SparkMD5.ArrayBuffer(),
        hash,
        suffix;
      spark.append(buffer);
      hash = spark.end();
      suffix = /\.([0-9a-zA-Z]+)$/i.exec(file.name)[1];

      // 创建100个切片
      let partList = [],
        partsize = file.size / 100,
        cur = 0;
      for (let i = 0; i < 101; i++) {
        let item = {
          chunk: file.slice(cur, cur + partsize),
          filename: ` ${hash}_${i}.${suffix}`,
        };
        cur += partsize;
        partList.push(item);
                      }

      this.partList = partList;
      this.hash = hash;
      this.sendRequest();
    },
    async sendRequest() {
      const totalChunks = 101;
      const requestList = Array.from({ length: totalChunks }, (_, i) => {
        if (this.uploadedIndices.includes(i)) return null;
        return () => this.uploadChunk(i);
      }).filter(Boolean);
      // 按顺序发送请求
      // console.log('1111111111111');

      let i = 0;
      const send = async () => {
        if (this.abort || i >= requestList.length) {


          if (i >= requestList.length) {
            // console.log('DDDDDDDDDDDDDDDDDDD');
            this.mergeRequest(totalChunks);
          }
          return;
        }
        await requestList[i]();
        i++;
        send();
      };
      send();
    },
    // 新增分片上传方法
    async uploadChunk(index) {
      const chunk = this.partList[index].chunk;
      const formData = new FormData();
      formData.append("chunk", chunk);
      formData.append("filename", this.partList[index].filename);

      await axios.post("/single3", formData, {
        headers: { "Content-Type": "multipart/form-data" },
        params: { index }
      }).then(res => {
        if (res.data.code === 0) {
          this.uploadedIndices.push(index);
          this.total++;
        }
      });
    },
    // 合并请求
    async mergeRequest(totalChunks) {
      // console.log('aaaaaaaaaaaaaaa');

      let result = await axios.get("/merge", {
        params: {
          hash: this.hash,
          fileName: this.Name,
          totalChunks
        }
      });
      result = result.data
      if (result.code === 0) {

        this.list.push({
          id: getId(),
          video: result.path,
          fileName: result.fileName,
          hash: result.hash
        });
        localStorage.setItem('uploadProgress', '');
        localStorage.setItem('list', JSON.stringify(this.list))
        this.btn = false
        this.uploadedIndices = [];
        this.total = 0
      }
    },
    // 修改后的暂停/继续方法
    handleBtn() {
      if (this.btn) {
        this.abort = false;
        this.btn = false;
        this.sendRequest();
      } else {
        localStorage.setItem('uploadProgress', JSON.stringify(this.uploadedIndices));
        this.btn = true;
        this.abort = true;
      }
    }
  },
};
</script>
<style scoped>
.sendfiled {
  margin-left: 80px;
}

.el-upload {
  margin: 0 auto;
  width: 1000px;
  height: 40px;
}

#app {
  box-sizing: border-box;
  padding: 20px;
  height: 100vh;
}

.uploadImg {
  margin-top: 20px;
  width: 360px;
}

.uploadImg img,
.uploadImg video {
  display: block;
  width: 100%;
}

.progress {
  box-sizing: border-box;
  padding: 0 10px;
  width: 150px;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list {
  display: flex;
  width: 1000px;
  height: 50px;
  line-height: 50px;
  justify-content: space-between;
  border: 1px solid black;
  align-items: center;
}

.list p {
  margin-left: 20px;
}

.list:nth-child(even) {
  background-color: #06eefa;
  /* 设置偶数行的背景色 */
}
</style>